package com.daoyin.ssph.action;

import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.daoyin.ssph.bean.Honor;
import com.daoyin.ssph.service.HonorService;


public class HonorAction {
	private HonorService ha;
	private String id;
	public void setId(String id) {
		this.id = id;
	}
	private File content;

	
	public void setHa(HonorService ha) {
		this.ha = ha;
	}
	
	public File getContent() {
		return content;
	}

	public void setContent(File content) {
		this.content = content;
	}
	private String contentFileName;
	

	public String getContentFileName() {
		return contentFileName;
	}

	public void setContentFileName(String contentFileName) {
		this.contentFileName = contentFileName;
	}
	
	
	public String upload()throws IOException{
		if(content == null){
			return "fail";
		}
		InputStream is = new FileInputStream(content);
		String root = ServletActionContext.getServletContext().getRealPath("common/upload");
		DateFormat format=new SimpleDateFormat("yyMMddHHmmss");
        String formatDate=format.format(new Date());
        int random=new Random().nextInt(100000);//鐢熸垚涓�釜闅忔満鏁�
        int position=contentFileName.lastIndexOf(".");//鑾峰彇鏂囦欢鍚庣紑鍚�鍦ㄧ伀鐙愭寚鍑鸿繖琛屾湁閿欍�
        String extension=contentFileName.substring(position);
        String newFileName=formatDate+random+extension;
		File distFile = new File(root,newFileName);
		OutputStream os = new FileOutputStream(distFile);
		byte[] buffer = new byte[400];
		int length = 0;
		while((length = is.read(buffer)) > 0){
			os.write(buffer,0,length);
		}

		is.close();
		os.close();

		//鏁版嵁搴撳瓨鏀句互涓嬭矾寰勶紝褰撻渶瑕佸湪椤甸潰鏄剧ず锛岀洿鎺ユ彁鍙栧嚭鏉ョ敤IMG鏍囩瑁呰浇鍗冲彲
		String imgurl ="./common/upload/" + distFile.getName();
		return imgurl;
	}
	
	public String add() throws IOException {
		ServletActionContext.getRequest().setCharacterEncoding("utf-8");
		Honor t = new Honor();
		String imgurl = upload();
		if(imgurl.equals("fail")){
			return "fail";
		}
		t.setImg(imgurl);
		t.setPublish(0);
		String str = ha.add(t);
		if(("success").equals(str)){
			return "success";
		}
		return "fail";			
	}

	HttpServletRequest request = null;

	public String show(){
		request = ServletActionContext.getRequest();

		List<Honor> list = ha.query();
		
		request.setAttribute("show", list);
		return "success";

	}
	public String publish(){
		request = ServletActionContext.getRequest();
		Honor honor = ha.query(Integer.parseInt(id));
		honor.setId(honor.getId());
		honor.setImg(honor.getImg());
		honor.setPublish(1);
		String str = ha.update(honor);
		if(("success").equals(str)){
			return "success";
		}
		return "fail";
	}
	public String delete(){
		ha.delete(Integer.parseInt(id));
		return "success";
	}
	
}
